package com.wangyi.im.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import static com.wangyi.im.enums.IMCodeEnum.IMCode;

import com.wangyi.im.response.IMResponse;
import retrofit2.Response;

import static com.wangyi.im.constants.CommonConstants.CODE;
import static com.wangyi.im.constants.CommonConstants.SIZE;
import static com.wangyi.im.constants.CommonConstants.DESC;


public class BuildDataUtil {
    public IMResponse buildData(Response<JSONObject> retrofitResponse, Class clazz, String dataKey){
        if (!retrofitResponse.raw().isSuccessful()) {
            throw new RuntimeException("网易云通信: 网络异常");
        }
        JSONObject responseJson = retrofitResponse.body();
        if(responseJson == null || !responseJson.containsKey(CODE)){
            throw new RuntimeException("网易云通信: 网络异常");
        }
        IMCode imCode = IMCode.getImCode(responseJson.getString(CODE));
        IMResponse.Builder builder = new IMResponse.Builder();/*.setCode(imCode.code).setMessage(imCode.desc);*/
        builder.setCode(imCode.code);
        if(responseJson.containsKey(DESC)){
            builder.setMessage(responseJson.getString(DESC));
        }
        if(IMCode.IM_200.code.equals(imCode.code) && responseJson.containsKey(dataKey)){
            builder.setData(JSON.toJavaObject(responseJson.getJSONObject(dataKey), clazz));
        }
        return builder.build();
    }

    public IMResponse buildListData(Response<JSONObject> retrofitResponse, Class clazz, String dataKey) {
        if (!retrofitResponse.raw().isSuccessful()) {
            throw new RuntimeException("网易云通信: 网络异常");
        }
        JSONObject responseJson = retrofitResponse.body();
        if(responseJson == null || !responseJson.containsKey(CODE)){
            throw new RuntimeException("网易云通信: 网络异常");
        }
        IMCode imCode = IMCode.getImCode(responseJson.getString(CODE));
        IMResponse.Builder builder = new IMResponse.Builder().setCode(imCode.code).setMessage(imCode.desc);
        if(IMCode.IM_200.code.equals(imCode.code) && responseJson.containsKey(SIZE)){
            builder.setSize(responseJson.getLongValue(SIZE));
        }
        if(IMCode.IM_200.code.equals(imCode.code) && responseJson.containsKey(dataKey)){
            builder.setData(responseJson.getJSONArray(dataKey).toJavaList(clazz));
        }
        return builder.build();
    }
}
